package com.feshfans.xmpp.client;

import com.feshfans.bridge.MessageBridge;
import com.feshfans.xmpp.XmppConnectionManager;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.chat2.IncomingChatMessageListener;
import org.jivesoftware.smack.chat2.OutgoingChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageClient extends AbstractListernerClient {

    private static final Logger Log = LoggerFactory.getLogger(MessageClient.class);
    private static final MessageBridge MESSAGE_NOTIFY = MessageBridge.getInstance();

    private static final MessageClient MESSAGE_CLIENT = new MessageClient(XmppConnectionManager.acquire());

    public static MessageClient getInstance(){
        return MESSAGE_CLIENT;
    }

    private ChatManager chatManager;

    MessageClient(XMPPTCPConnection connection) {
        super(connection);
        chatManager = ChatManager.getInstanceFor(connection);
        initListener();
    }

    @Override
    protected void initListener(){
        chatManager.addIncomingListener(new MyIncomingChatMessageListener());
        chatManager.addOutgoingListener(new MyOutgoingChatMessageListener());

    }
    public void sendMessage(String to,String message) throws XmppStringprepException, SmackException.NotConnectedException, InterruptedException {
        Chat chat = chatManager.chatWith(JidCreate.entityBareFrom(to));
        Message stanza = new Message();
        stanza.setType(Message.Type.chat);
        stanza.setBody(message);
        chat.send(stanza);
    }

    static class MyIncomingChatMessageListener implements IncomingChatMessageListener{

        @Override
        public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
            Log.info("收到来自 {} 的消息 {} ",from.getLocalpart(),message.getBody());
            MESSAGE_NOTIFY.newIncomingMessage(from, message, chat);
        }
    }

    static class MyOutgoingChatMessageListener implements OutgoingChatMessageListener{

        @Override
        public void newOutgoingMessage(EntityBareJid to, Message message, Chat chat) {
            Log.info("{} 发送消息 {} 至 {} ",message.getFrom(),message.getBody(),to.getLocalpart());
        }
    }
}
